<?php

namespace Util;

class HttpUtil
{

    public static $errno;

    public static function curlGet($url)
    {
        $headers = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); //超时秒数
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec($ch);
        self::$errno = curl_errno($ch);
        curl_close($ch);
        return $response;
    }

    public static function curlGetInfo($url)
    {
        $headers = array();
        $result = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); //超时秒数
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec($ch);
        self::$errno = curl_errno($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $result["http_code"] = $http_code;
        $result["data"] = $response;
        curl_close($ch);
        return $result;
    }

    public static function curlPost($url, $post_data, $header = '0')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $response = curl_exec($ch);
        self::$errno = curl_errno($ch);
        curl_close($ch);
        return $response;
    }

    public static function getURLQuery($data)
    {
        $query = '';
        if (is_array($data)) {
            foreach ($data as $key => $val) {
                if (is_null($val) || $val == '') {
                    continue;
                }
                if (is_bool($val)) {
                    $val = ($val) ? 1 : 0;
                }
                //多重数组递归调用
                $query .= '&' . $key . '=' . (is_array($val) ? self::assemble($val) : $val);
            }
        }
        return $query;
    }

}
